package com.lzc.tlmail.cart.tlmailcart.interceptor;

import com.lzc.common.constant.CartConstant;
import com.lzc.common.constant.OauthConstant;
import com.lzc.common.vo.MemberEntityVo;
import com.lzc.tlmail.cart.tlmailcart.to.UserInfoto;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author lzc
 * @create 2020-10-18 15:50
 */
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoto> userInfotoThreadLocal=new ThreadLocal<>();

    /**
     * 目标方法之前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        UserInfoto userInfoto = new UserInfoto();
        //先判断有没有登录
        HttpSession session = request.getSession();
        MemberEntityVo memberEntityVo = (MemberEntityVo) session.getAttribute(OauthConstant.OAUTH_LOGINUSER);
        if(memberEntityVo!=null){
            userInfoto.setUserId(memberEntityVo.getId());
        }
        Cookie[] cookies = request.getCookies();
        if(cookies!=null&&cookies.length>0){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals(CartConstant.Cart_USERKEY)){
                    userInfoto.setUserKey(cookie.getValue());
                }
            }
        }

        if(StringUtils.isEmpty(userInfoto.getUserKey())){
            String uuid= UUID.randomUUID().toString();
            userInfoto.setUserKey(uuid);
        }
        userInfotoThreadLocal.set(userInfoto);
        return true;
    }

    /**
     * 目标方法之后执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoto userInfoto = userInfotoThreadLocal.get();
        Cookie cookie = new Cookie(CartConstant.Cart_USERKEY,userInfoto.getUserKey());
        cookie.setDomain("tlmail.com");
        cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
        response.addCookie(cookie);
    }
}
